<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sessionStorage</title>
</head>
<body>
    <!-- 浏览器关了之后数据就没了 -->
    <h2>sessionStorage</h2>
    <button onclick="saveData()">点我保存一个数据</button><br><br>
    <button onclick="readData()">点我读取一个数据</button><br><br>
    <button onclick="deleteData()">点我删除一个数据</button><br><br>
    <button onclick="delAllData()">点我清空数据</button><br><br>

    <script type="text/javascript">
        let p = {name:'张三',age:18}
        // console.log(p.toString())

        function saveData() {
            // 如果第二个参数给的不是String类型的数据，它会自己调用toString方法转成String类型的数据
            sessionStorage.setItem("msg","hello!")
            sessionStorage.setItem("msg2",666)
            // sessionStorage.setItem("person",p)
            sessionStorage.setItem("person",JSON.stringify(p))
        }
        function readData() {
            console.log(sessionStorage.getItem('msg'))
            console.log(sessionStorage.getItem('msg2'))
            const result = sessionStorage.getItem('person');
            console.log(JSON.parse(result))
        
            // 读取不存在的数据返回的为null
            console.log(sessionStorage.getItem('msg3'))
            const result2 = sessionStorage.getItem('person2');
            // JSON.parse(null)返回的也是null
            console.log(JSON.parse(result2))
            
        }
        function deleteData() {
            sessionStorage.removeItem('msg2')
        }
        function delAllData() {
            sessionStorage.clear()
        }
    </script>
</body>
</html>